import base64
import gzip
import io

from django.test import TestCase

# Create your tests here.
# -*- coding: utf-8 -*-
import time
import json
import re
import hashlib
import requests
import datetime


class TSSHttpClient(object):
    def __init__(self, username="tapadmin", login_key="", host="127.0.0.1"):
        self.username = username
        self.url_prefix = 'https://{}:{}'.format(host, 443)
        self.auth_uri = "/skyeye/v1/admin/auth"
        self.init_secret(login_key)
        self.session = requests.Session()
        self.__login_process()

    def __login_process(self):
        self.__get_login_token()
        self.__login()

    def init_secret(self, login_key=""):
        CLIENT_ID = "mNSLP9UJCtBHtegjDPJnK3v"
        CLIENT_SECRET = "3460681205014671737"
        # 生成client_secret和client_id
        self.client_id = hashlib.sha256((CLIENT_ID + '|' + login_key).encode('utf-8')).hexdigest()
        self.client_secret = hashlib.sha256((CLIENT_SECRET + '|' + login_key).encode('utf-8')).hexdigest()
        self.timestamp = str(int(time.time()))
        raw = '{"client_id":\"%s\","username":\"%s\"}' % (self.client_id, self.username) + '%s%s' % (
            self.timestamp, self.client_secret)
        # 生成密钥
        self.signature = hashlib.sha256(raw.encode('utf-8')).hexdigest()

    def __get_login_token(self):
        "发送PSOT请求获取access_token"
        headers = {
            "X-Authorization": self.signature,
            "X-Timestamp": self.timestamp
        }
        data = {
            "client_id": self.client_id,
            "username": self.username
        }
        requests.packages.urllib3.disable_warnings()
        res = self.session.post(
            self.url_prefix + self.auth_uri,
            headers=headers,
            data=data,
            verify=False)
        res_dict = json.loads(res.text)
        token = res_dict.get("access_token", "")
        self.login_token = token

    def __login(self):
        "GET请求获取csrf_token"
        params = {"token": self.login_token}
        res = self.session.get(self.url_prefix + self.auth_uri, params=params, verify=False)

        # 获取session_id, 在cookie内
        cookies = requests.utils.dict_from_cookiejar(self.session.cookies)
        regular_csrf_tag = re.search(r"\<meta name=\"csrf-token\" content=\"[0-9a-fA-F]*\"", res.text)
        regular_csrf = re.search(r"[0-9a-fA-F]{16,32}", regular_csrf_tag.group())
        csrf_token = regular_csrf.group()
        self.csrf_token = csrf_token
        self.cookies = cookies

    def request(self, method, uri, **kwargs):
        requests.packages.urllib3.disable_warnings()
        # 添加cookie
        cookie = ''
        for name, value in self.cookies.items():
            cookie += '{0}={1};'.format(name, value)
        headers = {'cookie': cookie}
        res = requests.request(method=method, url=self.url_prefix + uri, headers=headers, verify=False, **kwargs)
        return res


def gzip_str(s):
    out = io.BytesIO()
    with gzip.GzipFile(fileobj=out, mode='w') as fo:
        fo.write(s.encode())

    bytes_obj = out.getvalue()
    return bytes_obj
